package xyz.lne.researchgroupmanage.util;

import com.google.common.collect.ImmutableMap;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import xyz.lne.researchgroupmanage.exception.BadRequestException;
import xyz.lne.researchgroupmanage.security.UserDetailsServiceImpl;
import xyz.lne.researchgroupmanage.service.dataTransferObject.JwtUserDTO;

/**
 * Designed By Lne.
 * 2021/1/29 15:28
 */
public class SecurityUtils {
    public static UserDetails getCurrentUser() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new BadRequestException(ImmutableMap.of("安全错误", "当前登录状态过期"));
        }
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            return UserDetailsServiceImpl.loadUserInCache(userDetails.getUsername());
        }
        throw new BadRequestException(ImmutableMap.of("安全错误", "找不到当前登录的信息"));
    }

    public static Integer getCurrentUserId() {
        JwtUserDTO jwtUserDTO = (JwtUserDTO) getCurrentUser();
        return jwtUserDTO.getUserId();
    }

    public static String getCurrentUsername() {
        final Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null) {
            throw new BadRequestException(ImmutableMap.of("安全错误", "当前登录状态过期"));
        }
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return userDetails.getUsername();
    }

    public static boolean removeUserInCache(String account){
        return UserDetailsServiceImpl.removeUserInCache(account);
    }
}
